package com.wtwd.device.service.impl;


import com.wtwd.device.service.CacheService;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zdl
 * @date 2022/7/25 14:13
 */
@Service
public class CacheServiceImpl implements CacheService {

    @Resource
    private CacheManager localCacheManager;

    @Override
    public <T> T getValue(String cacheName, Object key) {
        if (cacheName == null || key == null) {
            return null;
        }
        Cache cache = localCacheManager.getCache(cacheName);
        if (cache != null) {
            Cache.ValueWrapper valueWrapper = cache.get(key);
            if (valueWrapper != null) {
                return (T) valueWrapper.get();
            }
        }
        return null;
    }

    @Override
    public void putValue(String cacheName, Object key, Object value) {
        if (key == null || value == null) {
            return;
        }
        Cache cache = localCacheManager.getCache(cacheName);
        if (cache != null) {
            cache.put(key, value);
        }
    }

    @Override
    public void remove(String cacheName, Object key) {
        if (key == null) {
            return;
        }
        Cache cache = localCacheManager.getCache(cacheName);
        if (cache != null) {
            cache.evictIfPresent(key);
            cache.clear();
        }
    }
}
